# Packages ----------------------------------------------------------------

if(!require(pacman)){install.packages("pacman")}
pacman::p_load(tidyverse, scales, broom)


# Data --------------------------------------------------------------------

data <- read_dta("data/adopted_methods_public.dta")
data <- filter(data, view != "MiM") %>% 
  mutate(
    view = ifelse(view == "SBS", "IDM", "SDM")
  ) %>% 
  # Fix client with wrong ndm
  mutate(
    ndm = ifelse(client_id_nopii == 634, 1, ndm),
    d_imp = ifelse(client_id_nopii == 634, "Yes", d_imp),
  ) 

# Distribution method discussion ------------------------------------------

data %>% 
  select(d_iud, d_imp, d_inj, d_pil, d_lam, client_id_nopii, view) %>%
  pivot_longer(
    -c(client_id_nopii, view),
    names_prefix = "d_"
  ) %>% 
  mutate(
    name = case_when(name == "iud" ~ "IUD",
                     name == "imp" ~ "Implant",
                     name == "inj" ~ "Injectable",
                     name == "pil" ~ "Pill",
                     name == "lam" ~ "LAM"),
    value = ifelse(value == "Yes",1,0),
    value = ifelse(is.na(value),0, value)
  ) %>% 
  group_by(name, view) %>% 
  summarize(
    mean = mean(value, na.rm = TRUE),
    total = sum(value, na.rm = TRUE)
  ) %>%
  ggplot(
    aes(
      x = name,
      y = mean,
      fill = view
    )
  ) +
  geom_col(color = "black", position = "dodge") +
  geom_text(
    aes(
      label = paste0("N=",total, "\n", round(mean * 100,1), "%")
    ),
    position = position_dodge2(width = .9, preserve = "single"),
    vjust = -0.2,
    size = 3.5
  ) +
  labs(
    x = "Method",
    y = "",
    fill = "",
    title = "Fraction of clients who discussed each method in detail"
  ) + 
  scale_y_continuous(labels = percent, limits = c(0,0.8)) +
  scale_fill_manual(values = met.brewer("Kandinsky", 3)[2:3]) +
  theme_bw() +
  theme(
    panel.grid.minor = element_blank(), 
    panel.grid.major = element_blank(),
    legend.position = "bottom"
  )

ggsave("output/figures/FigS7-app_d_all.png", dpi = 320, scale = 0.9, height = 14, width = 20, units = "cm")
